using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using FlickrGrabbr.Model;
using System.Linq;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Controls;

namespace FlickrGrabbr.ViewModel
{
    /// <summary>
    /// This class contains properties that the main View can data bind to.
    /// <para>
    /// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
    /// </para>
    /// <para>
    /// You can also use Blend to data bind with the tool's support.
    /// </para>
    /// <para>
    /// See http://www.galasoft.ch/mvvm
    /// </para>
    /// </summary>
    public class MainViewModel : ViewModelBase
    {
        private IPhotos _photos;

        //Commands
        private RelayCommand _loadPhotos;

        public ObservableCollection<Photo> PhotoList { get; private set; }
        public Photo SelectedPhoto { get; private set; }

        /// <summary>
        /// Gets the MyCommand.
        /// </summary>
        public RelayCommand LoadPhotos
        {
            get
            {
                return _loadPhotos ?? (_loadPhotos = new RelayCommand(
                    ExecuteLoadPhotos,
                    CanExecuteLoadPhotos));
            }
        }

        private async void ExecuteLoadPhotos()
        {
            await _photos.Update();
            //RaisePropertyChanged(() => PhotoList);
            PhotoList = new ObservableCollection<Photo>(_photos.PhotoList);
            RaisePropertyChanged(() => PhotoList);
        }

        private bool CanExecuteLoadPhotos()
        {
            return true;
        }

        private RelayCommand<SelectionChangedEventArgs> _selectedPhotoChanged;

        /// <summary>
        /// Gets the MyCommand.
        /// </summary>
        public RelayCommand<SelectionChangedEventArgs> SelectedPhotoChanged
        {
            get
            {
                return _selectedPhotoChanged
                    ?? (_selectedPhotoChanged = new RelayCommand<SelectionChangedEventArgs>(
                       OnSelectedPhotoChanged));
            }
        }

        private void OnSelectedPhotoChanged(SelectionChangedEventArgs args)
        {
            Photo selectedPhoto = args.AddedItems.Cast<Photo>().FirstOrDefault();
            SelectedPhoto = selectedPhoto;
            RaisePropertyChanged(() => SelectedPhoto);
        }

        
        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel(IPhotos photos)
        {            
            _photos = photos;
            PhotoList = new ObservableCollection<Photo>(_photos.PhotoList);
        }
    }
}